package com.yami.shop.api.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.scheme.WxMaGenerateSchemeRequest;
import com.yami.shop.bean.model.WxRecord;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;

@RestController
@RequestMapping("/p/creat")
@AllArgsConstructor
@Slf4j
public class SchemeController {

    private WxMaService wxService;

    /**
     * 生成小程序码接口
     */
    @PostMapping("/scheme")
    public ResponseEntity<String> scheme(@Valid @RequestBody WxRecord wxRecord) throws Exception {
        log.debug("生成小程序码的时候获取到的表单记录id-----------》{}", wxRecord.getId());
        final Date date = DateUtils.addMinutes(new Date(), 20);  //  20分钟后失效
        final long expireTime = date.getTime() / 1000;
        WxMaGenerateSchemeRequest wxMaGenerateSchemeRequest = WxMaGenerateSchemeRequest.newBuilder()
                        .jumpWxa(WxMaGenerateSchemeRequest.JumpWxa.newBuilder()
                        .path("pages/news/index")
                        .query("id="+wxRecord.getId())
                        .build())
                        .isExpire(true)
                        .expireTime(expireTime)
                        .build();
        String generate = wxService.getWxMaSchemeService().generate(wxMaGenerateSchemeRequest);
        return ResponseEntity.ok(generate);
    }
}
